<?php



class ZduMobileAction extends BaseAction
{
    private $wechatId;
    private $resId;
    private $mRestaurant;
    private $mOrder;
    private $mOrderGoods;
    private $mData;
    private $mGoods;
    private $mGoodsCategory;
    private $mManager;
    private $mMessage;
    private $mRestaurantInfo;
    private $mWindow;
    private $mWeekRelation;
    private $mRestaurantData;
    private $module_name;
    private $mCart;
    private $restaurantId;

    public function _initialize()
    {
        $this->mOrder = D('Base/RestaurantOrder');
        $this->mRestaurant = D('Base/Restaurant');
        $this->mOrderGoods = D('Base/RestaurantOrderGoods');
        $this->mData = D('Base/RestaurantData');
        $this->mGoods = D('Base/RestaurantGoods');
        $this->mGoodsCategory = D('Base/RestaurantGoodsCategory');
        $this->mManager = D('Base/RestaurantManager');
        $this->mMessage = D('Base/RestaurantMessage');
        $this->mRestaurantInfo = D('Base/RestaurantInfo');
        $this->mWindow = D('Base/RestaurantWindow');
        $this->mWeekRelation = D('Base/RestaurantWeekRelation');
        $this->mRestaurantData = D('Base/RestaurantData');
        $this->mCart = D('Base/RestaurantCart');
        $action = array('notify','campusnotify');
        if (!in_array(strtolower(ACTION_NAME), $action)) {
            $resId = $this->_get('res_id');
            if (!$resId) {
                $this->error('参数错误');
            }

            $this->resId = $resId;
            // 查询模块信息
            $restaurant = $this->mRestaurant->getByPk($this->resId);
            if (!$restaurant) {
                $this->error('该模块暂未开通');
            }
            $restaurantInfo = M('RestaurantInfo')->where(array('res_id'=>$this->resId,'cut_off'=>0))->find();
            $this->restaurantId = $restaurantInfo['restaurant_id'];
            // 查询对应的模板
            if ($restaurant['module_name']) {
                $this->module_name = $restaurant['module_name'];
            } else {
                $this->module_name = 'Restaurant';
            }
            session('accountId', $restaurant['account_id']);
            $this->accountId = $restaurant['account_id'];
            if($this->isAlipayBrower()){
                $this->error("抱歉!请您使用微信客户端进行扫码点餐",5,'',1);
            }
            $this->login('zduMobile');
            $this->userId = session('userId');
            $this->accountId = session('accountId');
            $this->wechatId = session('wechatId');

            /*$this->userId = 247372;
            $this->accountId = 25;
            $this->wechatId = session('wechatId');*/

            $this->assign('title', $restaurant['title']);
            $this->assign('res_id', $restaurant['res_id']);
            $this->assign('account_id', $this->accountId);
            $this->assign('restaurantId',$this->restaurantId);
        }

    }

    /**
     *首页
     */
    public function index()
    {
        //是否关注
        if ($this->accountId == 59) { //正式服小乐惠，测试服云感
            $subscribe = M('WechatUser')->where(array('wechat_user_id' => session('wechatUserId')))->getField('subscribe');
            if ($subscribe == 0) {
                header('Location: ' . U('/base/html/xlhfocus'));
                exit;
            }
        }

        //根据wechat_id查询餐厅列表信息
        $condition = array('res_id' => $this->resId, 'cut_off' => 0);
        $limit = '';
        $res = $this->mRestaurantInfo->getList($condition, $limit);
//        $type = M('User')->where(array('user_id'=>$this->userId))->field('type')->find();
//        $type = implode(',',$type);
//        foreach ($res as $k=>$v){
//            $plus=0;
//            $v['selecte'] = explode(',',$v['selecte']);
//            foreach($v['selecte'] as $k1=>$v1){
//                if($v1==$type){
//                    $plus = 1;
//                }
//            }
//            if($plus!=1){
//                unset($res[$k]);
//            }
//        }

        $nowTime = time();
        foreach ($res as $key => $v) {
            $time1 = strtotime(date('Y-m-d') . ' ' . $v['time1'] . ':00');
            $time2 = strtotime(date('Y-m-d') . ' ' . $v['time2'] . ':00');
            $time3 = strtotime(date('Y-m-d') . ' ' . $v['time3'] . ':00');
            $time4 = strtotime(date('Y-m-d') . ' ' . $v['time4'] . ':00');
            $time5 = strtotime(date('Y-m-d') . ' ' . $v['time5'] . ':00');
            $time6 = strtotime(date('Y-m-d') . ' ' . $v['time6'] . ':00');
            if (($time1 <= $nowTime && $nowTime <= $time2) || ($time3 <= $nowTime && $nowTime <= $time4) || ($time5 <= $nowTime && $nowTime <= $time6)) {
                $res[$key]['stop'] = 0;
            } else {
                $res[$key]['stop'] = 1;
            }
            if ($v['user_num'] > 0) {
                $res[$key]['star'] = floor($v['score'] / $v['user_num']); //舍去法取整
                $res[$key]['grey_star'] = 5 - (floor($v['score'] / $v['user_num']));
            } else {
                $res[$key]['star'] = 0;
                $res[$key]['grey_star'] = 5;
            }

            if ($v['user_num2'] > 0) {
                $res[$key]['send_star'] = floor($v['score_send'] / $v['user_num2']); //舍去法取整
                $res[$key]['send_grey_star'] = 5 - (floor($v['score_send'] / $v['user_num2']));
            } else {
                $res[$key]['send_star'] = 0;
                $res[$key]['send_grey_star'] = 5;
            }

            if ($v['user_num3'] > 0) {
                $res[$key]['zl_star'] = floor($v['score_zl'] / $v['user_num3']); //舍去法取整
                $res[$key]['zl_grey_star'] = 5 - (floor($v['score_zl'] / $v['user_num3']));
            } else {
                $res[$key]['zl_star'] = 0;
                $res[$key]['zl_grey_star'] = 5;
            }
        }

        $data['list'] = $res;
        $name = $this->mRestaurant->getInfo(array('account_id' => $this->accountId));

        //$this->assign('page',$page->show());
        $this->assign('data', $data);
        $this->assign('name', $name);
        $this->display($this->module_name . ':index');

    }

    /**
     *菜单页
     */
    public function menu()
    {
        $url = "/restaurant/ZduMobile/myorder/res_id/" . $this->resId;
        $tablenoId = $this->_get("tableno_id");
        if($this->accountId = 59 && !$tablenoId){
            $this->error("请扫描餐桌二维码进入",3,$url,1);
        }
        if($tablenoId){
            $dataTable = M("RestaurantTableno")->where(array("tableno_id"=>$tablenoId,"cut_off"=>0))->find();

            if(!$dataTable){
                $this->error("桌号不存在",3,$url,1);
            }
            if($dataTable['status'] != 1){
                $this->error("桌号未启用",3,$url,1);
            }
            session("tableno_id",$tablenoId);
        }

        //是否关注
        if ($this->accountId == 59) { //正式服小乐惠，测试服云感
            $subscribe = M('WechatUser')->where(array('wechat_user_id' => session('wechatUserId')))->getField('subscribe');
            if ($subscribe == 0) {
                header('Location: ' . U('/base/html/xlhfocus'));
                exit;
            }
        }

        $restaurantId = $this->_get('restaurant_id');
        $list = array();
        if ($restaurantId) {
            //根据餐厅id查询所有商品种类
            $info = $this->mGoodsCategory->getList(array('restaurant_id' => $restaurantId, 'cut_off' => 0), '', 'sort asc');
            $categoryId = array();
            if ($info) {
                foreach ($info as $key => $v) {
                    $list[$v['category_id']] = $info[$key];
                    $categoryId[] = $v['category_id'];
                }
            }
            $goodsInfo = $this->mWeekRelation->getList(array('res_id' => $this->resId, 'week' => date('w')));
            $goodsId = array(0);
            if ($goodsInfo) {
                foreach ($goodsInfo as $v) {
                    $goodsId[] = $v['goods_id'];
                }
            }
            $category_id = 0;
            if ($categoryId) {
                foreach ($categoryId as $v) {
                    $res = $this->mGoods->getCount(array('goods_id' => array('in', $goodsId), 'category_id' => $v, 'cut_off' => 0, 'show' => 1));
                    if ($res > 0) {
                        $category_id = $v;
                        break;
                    }
                }
            }
        }

        //获取餐厅信息
        $info = $this->mRestaurantInfo->getByPk($restaurantId);
        $time1 = strtotime(date('Y-m-d') . ' ' . $info['time1'] . ':00');
        $time2 = strtotime(date('Y-m-d') . ' ' . $info['time2'] . ':00');
        $time3 = strtotime(date('Y-m-d') . ' ' . $info['time3'] . ':00');
        $time4 = strtotime(date('Y-m-d') . ' ' . $info['time4'] . ':00');
        $time5 = strtotime(date('Y-m-d') . ' ' . $info['time5'] . ':00');
        $time6 = strtotime(date('Y-m-d') . ' ' . $info['time6'] . ':00');
        $nowTime = time();
        if (($time1 <= $nowTime && $nowTime <= $time2) || ($time3 <= $nowTime && $nowTime <= $time4) || ($time5 <= $nowTime && $nowTime <= $time6)) {

        } else {
            $str = '';
            if($info['time1'] && $info['time1'] !="00:00" && $info['time2'] && $info['time2'] !="00:00"){
                $str .= $info['time1'] ."-". $info['time2']."  ";
            }
            if($info['time3'] && $info['time3'] !="00:00" && $info['time4'] && $info['time4'] !="00:00"){
                $str .= $info['time3'] ."-". $info['time4']."  ";
            }
            if($info['time5'] && $info['time5'] !="00:00" && $info['time6'] && $info['time6'] !="00:00"){
                $str .= $info['time5'] ."-". $info['time6']."  ";
            }
            $url = "/restaurant/ZduMobile/myorder/res_id/" . $this->resId;
            if($str) {
                $this->error("餐厅营业时间为：" . $str,3,$url,0);
            } else {
                $this->error("餐厅不在营业中",3,$url,0);
            }
        }
        $this->assign('restaurantId', $restaurantId);
        $this->assign('categoryId', $category_id > 0 ? $category_id : $categoryId[0]);
        $this->assign('info', $info);
        $this->assign('data', $list);
        $this->display($this->module_name . ':menu');
    }

    /**
     *餐厅详情
     */
    public function restaurant()
    {
        $sign = $this->_get('sign');  //为1的话视为从订单页访问的
        $restaurantId = $this->_get('id');
        $res = $this->mRestaurantInfo->getByPk($restaurantId);
        if ($res) {
            $nowTime = time();
            $time1 = strtotime(date('Y-m-d') . ' ' . $res['time1'] . ':00');
            $time2 = strtotime(date('Y-m-d') . ' ' . $res['time2'] . ':00');
            $time3 = strtotime(date('Y-m-d') . ' ' . $res['time3'] . ':00');
            $time4 = strtotime(date('Y-m-d') . ' ' . $res['time4'] . ':00');
            $time5 = strtotime(date('Y-m-d') . ' ' . $res['time5'] . ':00');
            $time6 = strtotime(date('Y-m-d') . ' ' . $res['time6'] . ':00');
            if (($time1 <= $nowTime && $nowTime <= $time2) || ($time3 <= $nowTime && $nowTime <= $time4) || ($time5 <= $nowTime && $nowTime <= $time6)) {
                $res['stop'] = 0;
            } else {
                $res['stop'] = 1;
            }

            if ($res['user_num'] > 0) {
                $res['star'] = floor($res['score'] / $res['user_num']); //舍去法取整
                $res['grey_star'] = 5 - (floor($res['score'] / $res['user_num']));
            } else {
                $res['star'] = 0;
                $res['grey_star'] = 5;
            }

            if ($res['user_num2'] > 0) {
                $res['send_star'] = floor($res['score_send'] / $res['user_num2']); //舍去法取整
                $res['send_grey_star'] = 5 - (floor($res['score_send'] / $res['user_num2']));
            } else {
                $res['send_star'] = 0;
                $res['send_grey_star'] = 5;
            }

            if ($res['user_num3'] > 0) {
                $res['zl_star'] = floor($res['score_zl'] / $res['user_num3']); //舍去法取整
                $res['zl_grey_star'] = 5 - (floor($res['score_zl'] / $res['user_num3']));
            } else {
                $res['zl_star'] = 0;
                $res['zl_grey_star'] = 5;
            }
        } else {
            $res = array();
        }
        $this->assign('sign', $sign);
        $this->assign('data', $res);
        $this->display($this->module_name . ':restaurant');
    }

    /**
     *我的订单
     */
    public function myOrder()
    {
        if ($this->_post('thirdsystem')) { //校园卡支付
            $dataResonse = $_POST;
            wLog(date('Y-m-d H:i:s') . ' myOrder dataResonse: ' . var_export($_POST,true), 'ZduMobile');
            if (!$dataResonse['sign']) {
                $this->error("参数错误");
            }
            $campus = Service('CampusCard/CampusCard');
            $resCampus = $campus->checkCampusOrder($dataResonse,2);
            wLog(date('Y-m-d H:i:s') . ' myOrder resCampus: ' . var_export($resCampus,true), 'ZduMobile');
            if($resCampus['status'] == 'S'){
                $this->campusNotify($resCampus['order_id'],$this->accountId);
            }
        }
        $type = $this->_get('type') ? $this->_get('type') : 1;
        $condition = array();
        $condition['user_id'] = $this->userId;
        if ($type == 2) {  //交易成功
            $condition['status'] = 4;
        } elseif ($type == 3) {  //等待配送
            $condition['status'] = 1;
        } elseif ($type == 4) {  //等待确认
            $condition['status'] = 2;
        } elseif ($type == 5) {  //等待评价
            $condition['status'] = 3;
        } elseif ($type == 6) {  //等待付款
            $condition['status'] = 0;
        }

        //根据fans_id查询用户的所有订单
        $info = $this->mOrder->relation(true)->getList($condition, '', 'create_time desc');

        if ($info) {
            foreach ($info as $key => $v) {
                foreach ($v['RestaurantOrderGoods'] as $val) {
                    $info[$key]['money_sum'] = ($info[$key]['money_sum'] ? $info[$key]['money_sum'] : 0) + $val['goods_num'] * $val['goods_price'];
                }
                $info[$key]['RestaurantOrderGoods']['count'] = count($v['RestaurantOrderGoods']);
            }
        }

        $this->assign('type', $type);
        $this->assign('data', $info);
        $this->display($this->module_name . ':myorder');
    }

    /**
     *确认下单
     */
    public function confirmOrders()
    {
        $orderId = $this->_get('order_id');
//		 $restaurantId = $this->_get('restaurant_id');
        $stime = $this->_get('stime');

        //校园卡状态
        $campusId = M('Campuscard')->where(array("account_id"=>$this->accountId,"status"=>1))->getField("campuscard_id");
        $campusCardCard = M('CampuscardCard')->where(array('user_id' => $this->userId,"campuscard_id"=>$campusId))->getField('status');
        $this->assign('campuscard_bind', $campusCardCard);
        if ($campusCardCard != 1) {
            $parameter = $this->resId . '||' . $orderId;
            $parameter = urlencode($parameter);
            $bindUrl = '/base/CampusCard/bound/account_id/' . $this->accountId . '/zdu_parameter/' . $parameter;
            $this->assign('bind_url', $bindUrl);
        }

        //根据订单号查询订单信息及订单物品表信息
        $res = $this->mOrder->relation(true)->getByPk($orderId);

        if ($res) {
            //计算总价
            $money = 0;
            foreach ($res['RestaurantOrderGoods'] as $v) {
                $money = $money + ($v['goods_price'] * $v['goods_num']);
            }
            $res['moneySum'] = $money;

            //根据餐厅id获取餐厅的营业时间并计算配送时间段
            $ret = $this->mRestaurantInfo->getByPk($res['restaurant_id']);
            if ($ret) {
                $nowTime = time();
                //高峰时间转换为时间戳
                $high_time1 = strtotime(date('Y-m-d') . ' ' . $ret['high_time1'] . ':00');
                $high_time2 = strtotime(date('Y-m-d') . ' ' . $ret['high_time2'] . ':00');
                $high_time3 = strtotime(date('Y-m-d') . ' ' . $ret['high_time3'] . ':00');
                $high_time4 = strtotime(date('Y-m-d') . ' ' . $ret['high_time4'] . ':00');

                $time1 = strtotime(date('Y-m-d') . ' ' . $ret['time1'] . ':00');
                if ($high_time1 <= $nowTime && $nowTime <= $high_time2) {
                    $time2 = strtotime(date('Y-m-d') . ' ' . $ret['time2'] . ':00') + $ret['need_time'] * 60 + 2700;
                } else {
                    $time2 = strtotime(date('Y-m-d') . ' ' . $ret['time2'] . ':00') + $ret['need_time'] * 60;
                }


                $time3 = strtotime(date('Y-m-d') . ' ' . $ret['time3'] . ':00');
                if ($high_time3 <= $nowTime && $nowTime <= $high_time4) {
                    $time4 = strtotime(date('Y-m-d') . ' ' . $ret['time4'] . ':00') + $ret['need_time'] * 60 + 2700;
                } else {
                    $time4 = strtotime(date('Y-m-d') . ' ' . $ret['time4'] . ':00') + $ret['need_time'] * 60;
                }

                $time_o = array();
                for ($i = $time1; $i < $time2; $i = $i + 900) {
                    if ($high_time1 <= $nowTime && $nowTime <= $high_time2) {
                        if ($i >= ($nowTime + $ret['need_time'] * 60 + 1800)) {     //高峰时段多半个小时的配送时间
                            $time_o[] = date('H:i', $i) . '~' . date('H:i', $i + 900);
                        }
                    } else {
                        if ($i >= ($nowTime + $ret['need_time'] * 60)) {
                            $time_o[] = date('H:i', $i) . '~' . date('H:i', $i + 900);
                        }
                    }

                }

                $time_t = array();
                for ($i = $time3; $i < $time4; $i = $i + 900) {
                    if ($high_time3 <= $nowTime && $nowTime <= $high_time4) {
                        if ($i >= ($nowTime + $ret['need_time'] * 60 + 1800)) {
                            $time_t[] = date('H:i', $i) . '~' . date('H:i', $i + 900);
                        }
                    } else {
                        if ($i >= ($nowTime + $ret['need_time'] * 60)) {
                            $time_t[] = date('H:i', $i) . '~' . date('H:i', $i + 900);
                        }
                    }

                }

                if ($this->accountId == 25) {
                    $time = array('10:30~11:00', '11:30~12:00', '12:30~13:00', '16:00~16:30', '17:00~17:30', '18:00~18:30');
                } else {
                    $time = array_merge($time_o, $time_t);
                }
                $this->assign('restaurantId', $ret['restaurant_id']);
                $this->assign('time', $time);
                $this->assign('shipment', $ret['shipment']);
                $this->assign('restaurant_id', $ret['restaurant_id']);
            }
        }

        if(session("tableno_id")){
            $tableName = M("RestaurantTableno")->where(array("tableno_id"=>session("tableno_id")))->getField("table_name");
            $this->assign("table_name",$tableName);
        }
        //$this->assign('address',$addressInfo);
        $this->assign('stime', $stime);
        $this->assign('order_id', $orderId);
        //$this->assign('notsend',$notsend);
        $this->assign('data', $res);
        $this->display($this->module_name . ':confirmorders');
    }

    /**
     *付款
     */
    public function orderPay()
    {
        $orderId = $this->_post('order_id');
        $restaurantId = $this->_post('restaurant_id');

        $memo = $this->_post('memo');
        $pay_type = $this->_post('pay_type');

        if (!$orderId) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '参数错误'));
        }
        //查询订单状态
        $orderInfo = $this->mOrder->getByPk($orderId);
        if ($orderInfo['status'] != 0) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '已经支付过了'));
        }

        //根据订单id获取订单商品表信息
        $orderGoodsInfo = $this->mOrderGoods->relation('restaurant_goods')->getList(array('order_id' => $orderId), array('goods_num', 'goods_price', 'goods_id'));

        $money = 0;
        $goodsName = array();
        $goodsNameCampusCard = array();
        if ($orderGoodsInfo) {
            foreach ($orderGoodsInfo as $v) {
                $goodsNameCampusCard[] = $v['restaurant_goods']['goods_name'];
                $money = $money + ($v['goods_num'] * $v['goods_price']);
                if ($v['restaurant_goods']['goods_sum'] <= 0) {
                    $goodsName[] = $v['restaurant_goods']['goods_name'];
                }
            }
        }

        if ($goodsName) {
            $str = implode('，', $goodsName);
            $this->ajaxReturn(array('status' => 'F', 'message' => $str . '等菜品库存不足，请重新选购'));
        }
        //查询餐厅的运费设置
        $restaurantInfo = $this->mRestaurantInfo->getByPk($restaurantId);
        // 判断餐厅是否营业中
        $nowTime = time();
        $time1 = strtotime(date('Y-m-d') . ' ' . $restaurantInfo['time1'] . ':00');
        $time2 = strtotime(date('Y-m-d') . ' ' . $restaurantInfo['time2'] . ':00');
        $time3 = strtotime(date('Y-m-d') . ' ' . $restaurantInfo['time3'] . ':00');
        $time4 = strtotime(date('Y-m-d') . ' ' . $restaurantInfo['time4'] . ':00');
        $time5 = strtotime(date('Y-m-d') . ' ' . $restaurantInfo['time5'] . ':00');
        $time6 = strtotime(date('Y-m-d') . ' ' . $restaurantInfo['time6'] . ':00');
        if (($time1 <= $nowTime && $nowTime <= $time2) || ($time3 <= $nowTime && $nowTime <= $time4) || ($time5 <= $nowTime && $nowTime <= $time6)) {
            $shipment = $restaurantInfo['shipment'];
            $order_amout = $money + ($shipment > 0 ? $shipment : 0);
            $order_amout = $order_amout ? round($order_amout, 2) : 0.00;
            //更新订单信息
            $data = array(
                'send_time' => date('Y-m-d') . ' ',
                'memo' => $memo,
                'order_amount' => $order_amout,
                'goods_amount' => $money,
                'freight' => $shipment > 0 ? $shipment : 0
            );
            $ret = M('RestaurantOrder')->where(array('order_id' => $orderId))->save($data);
            if ($ret === false) {
                $this->ajaxReturn(array('status' => 'F', 'message' => '更新订单失败'));
            }
            //获取订单信息
            $order = $this->mOrder->getByPk($orderId);
            if ($pay_type == 4) { //校园卡支付
                //跳转地址
                $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                $redirectUrl = $protocol . $_SERVER['HTTP_HOST'];
                $thirdurl = $redirectUrl . '/restaurant/ZduMobile/myOrder/res_id/' . $this->resId;
                $errorurl = $redirectUrl . '/restaurant/ZduMobile/myOrder/res_id/' . $this->resId;
                $goodsNameCampusCard = implode(',', $goodsNameCampusCard);
                $campus = Service('CampusCard/CampusCard');
                $resCampus = $campus->campusCardPay($this->accountId,$this->userId,$order, $thirdurl, $errorurl,2,$goodsNameCampusCard);
                wLog(date('Y-m-d H:i:s') . ' orderPay resCampus: ' . var_export($resCampus,true), 'ZduMobile');
                if ($resCampus['status'] == 'S') {
                    $this->ajaxReturn(array('status' => 'CampusCard', 'message' => '连接校园卡成功', 'data' => $resCampus['data']));
                } else {
                    $this->ajaxReturn(array('status' => 'F', 'message' => $resCampus['message']));
                }
            } else { //微信支付

            }
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '该餐厅已停止营业'));
        }
    }

    /**
     * 校园卡支付成功之后异步通知业务逻辑处理
     * @param $orderId
     * @param $account_id
     */
    public function campusNotify($orderId,$account_id)
    {
        wLog(date('Y-m-d H:i:s') . ' campusNotify enter: ' .$orderId, 'ZduMobile');
        $orderStatus = M('RestaurantOrder')->where(array('order_id' => $orderId))->getField('status');
        if ($orderStatus == 1) {
            wLog(date('Y-m-d H:i:s') . ' campusNotify has update: ' . M()->_sql(), 'ZduMobile');
            return false;
        }
        //生成餐桌号
        $orderNum = RedisService::keyExists('zdOrderNum');
        if ($orderNum) {
            $orderNum = RedisService::incr('zdOrderNum', 1);
        } else {
            RedisService::set('zdOrderNum', 1);
            $orderNum = RedisService::get('zdOrderNum');
        }
        $save_data = array(
            'status' => 1,
            'pay_type' => 4,
            'pay_time' => time(),
            'is_pay_notify' => 1,
            'order_num' => $orderNum
        );
        M('RestaurantOrder')->where(array('order_id' => $orderId))->save($save_data);
        wLog(date('Y-m-d H:i:s') . ' campusNotify RestaurantOrder save: ' .M()->_sql(), 'ZduMobile');
        M('RestaurantOrderGoods')->where(array('order_id' => $orderId))->save(array('order_num' => $orderNum, 'pay_status' => 1));
        wLog(date('Y-m-d H:i:s') . ' campusNotify RestaurantOrderGoods save: ' .M()->_sql(), 'ZduMobile');
        // 减库存,加销量
        $this->notify($orderId, $account_id);
    }

    /**
     * 微支付异步通知
     */
    public function notify($orderId, $accountId = '')
    {

        if ($orderId) {
            $mOrder = D('Base/RestaurantOrder');
            $orderInfo = $mOrder->getByPk($orderId);

            if (($orderInfo['status'] == 1 || $orderInfo['status'] == 2) && $orderInfo['is_pay_notify'] == 1) {
//                $M_og = M("restaurant_order_goods");
//                $res = $M_og->where("order_id = 165")->save(array('order_num' => 55));

                import("@.Msgtpl.Base.RestaurantMsgtpl");
                $wechatInfo = D('Wechat/Wechat')->getInfo(array('account_id' => $accountId), array('wechat_id'));
                $RestaurantMsgtpl = new RestaurantMsgtpl($wechatInfo['wechat_id']);
                // 发送消息给用户
                $RestaurantMsgtpl->sendMessage($orderInfo, $accountId);

                // 发送消息给档口管理员
                $RestaurantMsgtpl->sendMessageToManage($orderInfo, $accountId);

                // 减库存,加销量
                $this->changeGoodsNum($orderId);
                // 打印小票
                $this->useWifiPrintInfo($orderId);
            }
        }
    }

    /**
     *加销量，减库存
     * @param string $order_id
     */
    public function changeGoodsNum($order_id)
    {
        $info = D('Base/RestaurantOrderGoods')->getList(array('order_id' => $order_id));
        if ($info) {
            foreach ($info as $v) {
                D('Base/RestaurantGoods')->changeNum(array('goods_id' => $v['goods_id']), $v['goods_num']);
            }
        }
    }

    /**
     *评价订单
     */
    public function comment()
    {
        $score = $this->_post('score');
        $scoreSend = $this->_post('score_send');
        $scoreZl = $this->_post('score_zl');
        $restaurantId = $this->_post('id');
        $orderId = $this->_post('order_id');
        $comment = $this->_post('comment');
        //查询订单状态
        $info = $this->mOrder->getByPk($orderId);
        if ($info['status'] == 3) {
            //评分
            $ret = $this->mRestaurantInfo->comment(array('restaurant_id' => $restaurantId), $score, $scoreSend, $scoreZl);
            //将订单状态改为已评价
            $res = $this->mOrder->update(array('order_id' => $orderId, 'status' => 4, 'finish_time' => time(), 'comment' => $comment));
            if ($ret && $res) {
                $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功'));
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '操作失败'));
            }
        } elseif ($info['status'] == 4) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '您已评价过了'));
        } elseif ($info['status'] < 3 || $info['status'] > 4) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '评价失败'));
        }
    }

    /**
     *取消订单
     */
    public function resetOrder()
    {
        $orderId = $this->_post('order_id');
        //查询订单状态
        $info = $this->mOrder->getByPk($orderId);
        if ($info['status'] == 0) {
            //将订单状态改为已取消
            $res = $this->mOrder->update(array('order_id' => $orderId, 'status' => 7, 'reset_time' => time(), 'reset_reason' => '用户自助取消'));
            if ($res) {
                $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功'));
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '操作失败'));
            }
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '该订单不能取消'));
        }
    }

    /**
     *确认收货
     */
    public function sureOrder()
    {
        $orderId = $this->_post('order_id');
        //查询订单状态
        $info = $this->mOrder->getByPk($orderId);
        if ($info['status'] == 2) {
            //将订单状态改为已收货
            $res = $this->mOrder->update(array('order_id' => $orderId, 'status' => 3, 'receive_time' => time()));
            if ($res) {
                $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功'));
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '操作失败'));
            }
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '该订单不能确认收货'));
        }
    }

    /**
     *订单详情
     */
    public function orderDetail()
    {
        $orderId = $this->_get('order_id');
        if (!$orderId) {
            echo '<script>alert("参数错误");history.back();</script>';
            exit();
        } else {
            //查询订单信息
            $info = $this->mOrder->relation(true)->getByPk($orderId);

            if ($info) {
                //查询管理员信息
                $manager = $this->mManager->getInfo(array('res_id' => $this->resId, 'restaurant_id' => $info['restaurant_id'], 'cut_off' => 0), array('username', 'mobile', 'wechat_user_id'));
                $tableName = M("RestaurantTableno")->where(array("tableno_id"=>$info['tableno_id']))->getField("table_name");
                if($tableName){
                    $info['table_name'] = $tableName;
                }
                if ($manager) {
                    $this->assign('manager_name', $manager['username']);
                    $this->assign('manager_mobile', $manager['mobile']);
                    // $info['manager_name'] = $manager['username'];
                    // $info['manager_mobile'] = $manager['mobile'];
                }
                foreach ($info['RestaurantOrderGoods'] as $key => $v) {
                    $info['money_sum'] = ($info['money_sum'] ? $info['money_sum'] : 0) + $v['goods_num'] * $v['goods_price'];
                }
                $count = count($info['RestaurantOrderGoods']);
            } else {
                $info = array();
                $count = 0;
            }
        }
        $this->assign('count', $count);
        $this->assign('data', $info);
        $this->display($this->module_name . ':orderdetail');
    }

    /**
     *获取单个分类下的所有商品信息
     */
    public function getGoodsInfo()
    {
        $categoryId = $this->_get('category_id');
        $restaurantId = $this->_get('restaurant_id');

        if (!$categoryId || !$restaurantId) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '参数错误'));
        } else {
            $data = array();
            //根据种类id和餐厅id查询所有商品信息
            $condition = array('restaurant_id' => $restaurantId, 'category_id' => $categoryId, 'cut_off' => 0, 'show' => 1, 'goods_sum' => array('gt', 0));
            $need = array('category_id', 'goods_id', 'goods_name', 'goods_desc', 'goods_sum', 'price', 'discount', 'goods_logo', 'saled_num');
            //获取当天供应的商品id
            $week = date('w');
            $weekGoods = $this->mWeekRelation->getList(array('res_id' => $this->resId, 'week' => $week), array('goods_id'));
            $weekGoodsId = array(0);
            if ($weekGoods) {
                foreach ($weekGoods as $v) {
                    $weekGoodsId[] = $v['goods_id'];
                }
            }

            $condition['goods_id'] = array('in', $weekGoodsId);
            $list = $this->mGoods->getList($condition, $need);
            //查询购物车信息
            $cartInfo = $this->mCart->relation(true)->getList(array('user_id' => $this->userId, 'restaurant_id' => $restaurantId));
//			var_dump($cartInfo);die();
            $cart_sum = 0;
            $cart_cost = 0;
            if ($cartInfo) {
                $cart_sum = count($cartInfo);
                foreach ($cartInfo as $v) {
                    if ($v['restaurant_goods']['discount'] == '0.00') {
                        $cart_cost = $cart_cost + ($v['goods_num'] * $v['restaurant_goods']['price']);
                    } else {
                        $cart_cost = $cart_cost + ($v['goods_num'] * $v['restaurant_goods']['discount']);
                    }
                }
            }

            $goodsId = array(0);
            foreach ($list as $v1) {
                $goodsId[] = $v1['goods_id'];

            }

            $cartNumInfo = $this->mCart->getList(array('goods_id' => array('in', $goodsId), 'user_id' => $this->userId, 'restaurant_id' => $restaurantId), array('goods_id', 'goods_num'));
            $cartNumInfo1 = array();

            foreach ($cartNumInfo as $ky => $vl) {
                $cartNumInfo1[$vl['goods_id']] = $vl['goods_num'];
            }

            foreach ($list as $key => $val) {
                $list[$key]['sale_num'] = $cartNumInfo1[$val['goods_id']] ? $cartNumInfo1[$val['goods_id']] : 0;
                if ($val['discount'] == '0.00') {
                    $list[$key]['discount'] = 0;
                }
            }
            //查询店铺信息
            $res = $this->mRestaurantInfo->getByPk($restaurantId);
            if ($res) {
                $minPrice = $res['min_price'];
            } else {
                $minPrice = 0.00;
            }

            if ($list) {
                $data['status'] = 'S';
                $data['message'] = '查询成功';
                $data['data']['goods_list'] = $list;
                $data['data']['cart_sum'] = $cart_sum;
                $data['data']['cart_cost'] = $cart_cost;
                $data['data']['restaurant_id'] = (int)$restaurantId;
                $data['data']['min_price'] = $minPrice;
            } else {
                $data['status'] = 'S';
                $data['message'] = '查询失败';
                $data['data']['restaurant_id'] = (int)$restaurantId;
                $data['data']['cart_cost'] = $cart_cost;

            }
//			var_dump($data);die();
            $this->ajaxReturn($data);
        }
    }

    /**
     *购物车添加、减少商品数量接口
     */
    public function updateCartNum()
    {
        $restaurantId = $this->_get('restaurant_id');
        $goodsId = $this->_get('goods_id');
        $goodsNum = $this->_get('sale_num') ? $this->_get('sale_num') : 0;

        if (!$restaurantId || !$goodsId) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '参数错误'));
        } else {
            //根据餐厅id查询餐厅信息
            $info = $this->mRestaurantInfo->getInfo(array('restaurant_id' => $restaurantId, 'cut_off' => 0));

            if (!$info) {
                $this->ajaxReturn(array('status' => 'F', 'message' => '餐厅不存在'));
            }

            if ($goodsNum == 0) {  //删除购物车物品
                $condition = array(
                    'restaurant_id' => $restaurantId,
                    'goods_id' => $goodsId,
                    'user_id' => $this->userId,
                );
                $res = $this->mCart->where($condition)->delete();
                if ($res === 0) {
                    $res = true;
                }
            } else {  //添加购物车
                $data = array(
                    'restaurant_id' => $restaurantId,
                    'goods_id' => $goodsId,
                    'goods_num' => $goodsNum,
                    'user_id' => $this->userId,
                );
                $ret = $this->mCart->getInfo(array('goods_id' => $goodsId, 'user_id' => $this->userId, 'restaurant_id' => $restaurantId));
                if ($ret) {
                    $res = $this->mCart->where(array('cart_id' => $ret['cart_id']))->save($data);
                } else {
                    $res = $this->mCart->add($data);
                }
            }

            //查询购物车信息
            $cartInfo = $this->mCart->relation(true)->getList(array('user_id' => $this->userId, 'restaurant_id' => $restaurantId));
            $cart_sum = 0;
            $cart_cost = 0;
            if ($cartInfo) {
                $cart_sum = count($cartInfo);
                foreach ($cartInfo as $v) {
                    if ($v['restaurant_goods']['discount'] == '0.00') {
                        $cart_cost = $cart_cost + ($v['goods_num'] * $v['restaurant_goods']['price']);
                    } else {
                        $cart_cost = $cart_cost + ($v['goods_num'] * $v['restaurant_goods']['discount']);
                    }
                }
            }
//			var_dump($cartInfo);
//			var_dump($cart_cost);die();
            //查询当前物品的单价
            $goodsInfo = $this->mGoods->getByPk($goodsId);
            if ($goodsInfo['discount'] == '0.00') {
                $good_price = number_format($goodsInfo['price'] * $goodsNum);
            } else {
                $good_price = number_format($goodsInfo['discount'] * $goodsNum);
            }

            if ($res !== false) {
                $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功', 'data' => array('cart_sum' => $cart_sum, 'cart_cost' => $cart_cost, 'min_price' => $info['min_price'], 'goods_price' => $good_price, 2, '.', ' ')));
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '操作失败'));
            }
        }
    }

    /**
     *查询购物车信息
     */
    public function getCartInfo()
    {
        $restaurantId = $this->_get('restaurant_id');
        if ($restaurantId) {
            $cartInfo = $this->mCart->relation(true)->getList(array('user_id' => $this->userId, 'restaurant_id' => $restaurantId));
            $list = array();
            if ($cartInfo) {
                foreach ($cartInfo as $key => $v) {
                    $list[$key]['cart_id'] = $v['cart_id'];
                    $list[$key]['goods_id'] = $v['goods_id'];
                    $list[$key]['sale_num'] = $v['goods_num'];
                    if ($v['restaurant_goods']['discount'] == '0.00') {
                        $list[$key]['price'] = $v['restaurant_goods']['price'] * $v['goods_num'];
                    } else {
                        $list[$key]['price'] = $v['restaurant_goods']['discount'] * $v['goods_num'];
                    }
                    $list[$key]['goods_name'] = $v['restaurant_goods']['goods_name'];
                }
            }
            $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功', 'data' => $list));
        } else {
            $this->ajaxReturn(array('status' => 'S', 'message' => '参数错误'));
        }
    }

    /**
     *购物车结算接口
     */
    public function getOrderUrl()
    {
        $restaurantId = $this->_get('restaurant_id');
        //查询餐厅起送价
        $info = $this->mRestaurantInfo->getByPk($restaurantId);
        // 判断餐厅是否营业中
        $nowTime = time();
        $time1 = strtotime(date('Y-m-d') . ' ' . $info['time1'] . ':00');
        $time2 = strtotime(date('Y-m-d') . ' ' . $info['time2'] . ':00');
        $time3 = strtotime(date('Y-m-d') . ' ' . $info['time3'] . ':00');
        $time4 = strtotime(date('Y-m-d') . ' ' . $info['time4'] . ':00');
        $time5 = strtotime(date('Y-m-d') . ' ' . $info['time5'] . ':00');
        $time6 = strtotime(date('Y-m-d') . ' ' . $info['time6'] . ':00');
        if (($time1 <= $nowTime && $nowTime <= $time2) || ($time3 <= $nowTime && $nowTime <= $time4) || ($time5 <= $nowTime && $nowTime <= $time6)) {
            //查询当前用户购物车中当前餐厅的所有商品
            if ($restaurantId) {
                $cartInfo = $this->mCart->relation(true)->getList(array('user_id' => $this->userId, 'restaurant_id' => $restaurantId));
                $goodsList = array();
                $moneySum = 0;
                foreach ($cartInfo as $key => $v) {
                    if ($v['goods_num'] > $v['restaurant_goods']['goods_sum']) {
                        $goodsList[] = $v['restaurant_goods']['goods_name'];
                    }
                    if ($v['restaurant_goods']['discount'] == '0.00') {
                        $moneySum = $moneySum + $v['goods_num'] * $v['restaurant_goods']['price'];
                    } else {
                        $moneySum = $moneySum + $v['goods_num'] * $v['restaurant_goods']['discount'];
                    }
                }
                if ($moneySum < $info['min_price']) {
                    $this->ajaxReturn(array('status' => 'F', 'message' => '未达到起送价'));
                }

                if (!empty($goodsList)) {
                    $str = implode('，', $goodsList);
                    $this->ajaxReturn(array('status' => 'F', 'message' => $str . '等菜品库存不足，请重新选购'));
                }

                if ($cartInfo) {
                    //获取订单号
                    $orderSn = $this->getOrderSn('Restaurant');
                    //生成订单
                    $data = array();
                    $data['order_sn'] = $orderSn['data'];  //生成订单号
                    $data['status'] = 0;
                    $data['user_id'] = $this->userId;
                    $data['res_id'] = $this->resId;
                    $data['restaurant_id'] = $restaurantId;
                    $data['create_time'] = time();
                    $data['is_pay_notify'] = 0;
                    $data['tableno_id'] = session("tableno_id");
                    //往订单表插入数据
                    $ret = $this->mOrder->add($data);
                    if ($ret) {
                        //将购物车中的商品写入订单物品表
                        //var_dump($cartInfo);die;
                        foreach ($cartInfo as $v) {
                            if ($v['restaurant_goods']['discount'] == '0.00') {
                                $good_price = $v['restaurant_goods']['price'];
                            } else {
                                $good_price = $v['restaurant_goods']['discount'];
                            }
                            $orderGoodsInfo[] = array(
                                'order_id' => $ret,
                                'goods_id' => $v['goods_id'],
                                'restaurant_id' => $restaurantId,
                                'goods_num' => $v['goods_num'],
                                'create_time' => time(),
                                'user_id' => $this->userId,
                                'goods_name' => $v['restaurant_goods']['goods_name'],
                                'goods_price' => $good_price,
                                'goods_logo' => $v['restaurant_goods']['goods_logo'],
                                'category_id' => $v['restaurant_goods']['category_id'],
                                'window_id' => M('RestaurantGoodsCategory')->where(array('category_id'=>$v['restaurant_goods']['category_id']))->getField('window_id'),
                                'tableno_id'=> session("tableno_id")
                            );
                        }
                        $res = $this->mOrderGoods->addAll($orderGoodsInfo);
                        if ($res !== false) {
                            //删除购物车表该用户当然餐厅的数据
                            $this->mCart->where(array('user_id' => $this->userId, 'restaurant_id' => $restaurantId))->delete();
                            $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功', 'url' => '/index.php?g=restaurant&m=ZduMobile&a=confirmorders&res_id=' . $this->resId . '&order_id=' . $ret));
                        } else {
                            $this->ajaxReturn(array('status' => 'F', 'message' => '插入订单物品失败'));
                        }
                    } else {
                        $this->ajaxReturn(array('status' => 'F', 'message' => '生成订单失败'));
                    }
                } else {
                    $this->ajaxReturn(array('status' => 'F', 'message' => '请选择商品'));
                }
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '参数错误'));
            }
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '该餐厅已停止营业'));
        }
    }

    /**
     *发货列表页面
     */
    public function sendList()
    {
        //查询是否是管理员
        $manager = $this->mManager->getList(array('res_id' => $this->resId, 'wechat_user_id' => session('wechatUserId'), 'cut_off' => 0));
        if (empty($manager)) {
            $this->error('对不起，你不是餐厅管理员，无法操作！');
        }

        $num = 10;
        $condition = array('res_id' => $this->resId, 'status' => array('in', array(1, 2, 3, 4)));
        $count = $this->mOrder->getCount($condition);
        $page = new Page($count, $num);
        $limit = $page->firstRow . ',' . $page->listRows;;
        //查询状态为已付款，已发货，已确认收货，已评价的订单
        $list = $this->mOrder->relation('RestaurantOrderGoods')->getList($condition, '', 'status asc,pay_time desc', '', $limit);
        $this->assign('pageCount', ceil($count / $num));
        $this->assign('data', $list);
        $this->display($this->module_name . ':sendlist');
    }

    /**
     *滑动加载发货列表
     */
    public function ajaxGetList()
    {
        //查询该微信下的所有餐厅
        $num = 10;
        $condition = array('res_id' => $this->resId, 'status' => array('in', array(1, 2, 3, 4)));
        $count = $this->mOrder->getCount($condition);
        $page = new Page($count, $num);
        $limit = $page->firstRow . ',' . $page->listRows;;
        //查询状态为已付款，已发货，已确认收货，已评价的订单
        $list = $this->mOrder->relation('RestaurantOrderGoods')->getList($condition, '', 'status asc,pay_time desc', '', $limit);
        $data = array();
        if ($list) {
            foreach ($list as $key => $val) {
                $data[$key]['order_id'] = $val['order_id'];
                $data[$key]['order_sn'] = $val['order_sn'];
                $data[$key]['pay_time'] = date('Y-m-d H:i', $val['pay_time']);
                $data[$key]['user_name'] = $val['user_name'];
                $data[$key]['status'] = $val['status'];
                $data[$key]['mobile'] = $val['mobile'];
                $data[$key]['address'] = $val['address'];
                if ($val['RestaurantOrderGoods']) {
                    $str = '';
                    foreach ($val['RestaurantOrderGoods'] as $v) {
                        $str = $str . '<p>' . $v['goods_name'] . '<span class="pull-right">x' . $v['goods_num'] . '</span></p>';
                    }
                    $data[$key]['goods_info'] = $str;
                } else {
                    $data[$key]['goods_info'] = '';
                }

            }
        }
        $this->ajaxReturn(array('status' => 'S', 'data' => $data));
    }

    /**
     *发货操作
     */
    public function send()
    {
        $id = $this->_post('id');
        //查询是否是管理员
        $manager = $this->mManager->getInfo(array('res_id' => $this->resId, 'wechat_user_id' => session('wechatUserId'), 'cut_off' => 0));
        if (empty($manager)) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '对不起，你不是餐厅管理员，无法操作！'));
        }

        //修改订单状态
        $res = $this->mOrder->update(array('order_id' => $id, 'status' => 2, 'ship_time' => time(), 'send_user' => $manager['username']));
        if ($res) {
            //查询订单信息
            $orderInfo = $this->mOrder->getByPk($id);
            import("@.Msgtpl.Base.RestaurantMsgtpl");
            $accountInfo = D('Restaurant')->getInfo(array('res_id' => $this->resId), array('account_id'));
            $wechatInfo = D('Wechat')->getInfo(array('account_id' => $accountInfo['account_id']), array('wechat_id'));
            $RestaurantMsgtpl = new RestaurantMsgtpl($wechatInfo['wechat_id']);
            $RestaurantMsgtpl->sendInfoToUser($orderInfo, $accountInfo['account_id']);
            $this->ajaxReturn(array('status' => 'S', 'message' => '发货成功'));
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '发货失败'));
        }
    }

    /**
     *打印信息
     * @param $orderId
     */
    public function useWifiPrintInfo($orderId)
    {
        //$orderId=8;
        $mOrder = D('Base/RestaurantOrder');
        $mGoods = D('Base/RestaurantGoods');
        $mWindow = D('Base/RestaurantWindow');
        //$orderId = $this->_get('order_id');
        //查询订单信息
        $info = $mOrder->relation(true)->getByPk($orderId);
        //$info = $this->mOrder->relation(true)->getByPk($orderId);
        if ($info) {
            $goodsCold = array();
            $windowInfo = array();

            foreach ($info['RestaurantOrderGoods'] as $key => $v) {
                //查询菜品对应的种类对应档口及打印机信息
                $list = $mGoods->relation('RestaurantGoodsCategory')->getByPk($v['goods_id']);
                //$list = $this->mGoods->relation('RestaurantGoodsCategory')->getByPk($v['goods_id']);
                $wInfo = $mWindow->getByPk($list['window_id']);
                //$wInfo = $this->mWindow->getInfo($list['window_id']);
                $windowInfo[$wInfo['window_id']]['window_id'] = $wInfo['window_id'];
                $windowInfo[$wInfo['window_id']]['print_key'] = $wInfo['print_key'];
                $windowInfo[$wInfo['window_id']]['print_dno'] = $wInfo['print_dno'];
                $windowInfo[$wInfo['window_id']]['print_username'] = $wInfo['print_username'];
                $windowInfo[$wInfo['window_id']]['print_count'] = $wInfo['print_count'];
                $goodsCold[$v['window_id']][] = str_pad($v['goods_name'],18,'　'). str_pad($v['goods_num'],4).'￥'.number_format($v['goods_num']*$v['goods_price'],2)  . '\n';
                $windowInfo[$wInfo['window_id']]['order_amount'] += $v['goods_num']*$v['goods_price'];
                //$goodsHot = $goodsHot . $v['goods_name'] . '    ' . $v['goods_num'] . '     ' . $v['goods_num']*$v['goods_price'] . '\n';
            }
            foreach ($goodsCold as $one=>$on){
                $windowInfo[$one]['goods'] = implode('',$on);
            }
            $headerStr = '';
            if ($this->accountId == 2) {
                $headerStr = '|2http://weixin.qq.com/r/7UzVzQPEGF5nrUeu9xn-' . '\r\n';
            }
            if ($windowInfo) {
                if($info['pay_type'] == 1){
                    $payType = '微信';
                }
                if($info['pay_type'] == 2){
                    $payType = '支付宝';
                }
                if($info['pay_type'] == 4){
                    $payType = '一卡通';
                }
                if($info['pay_type'] == 5){
                    $payType = '校园卡';
                }
                foreach ($windowInfo as $val) {
                    $content = $headerStr .
                        '|5================================' . '\r\n' .
                        '|4餐厅名：' . $info['RestaurantInfo']['restaurant_name'] . '\r\n' .
                        '|4餐号：' . $info['order_num'] . '\r\n';
                    if($info['tableno_id']){
                        $content .=  '|4桌号：' . $info['tableno_id'] . '\r\n';
                    }
                    $content .= '|5订单编号：' . $info['order_sn'] . '\r\n' .
                        '|5打印时间:'. date('Y-m-d H:i:s') . '\n' .
                        '|5支付方式:'. $payType . '\n' .
                        '|4------------------------' . '\n' .
                        str_pad('商品名称',18,'　').str_pad('数量',8).'小计'.'\n' .$val['goods'] .
                        '------------------------' . '\n' .
                        '总计：' . $val['order_amount'] .'元'. '\n';
                    $str = $val['print_key'] . $val['print_dno'] . 'aykj';
                    $keyInfo = md5($str);
                    $username = $val['print_username'];
                    $dno = $val['print_dno'];
                    $times = $val['print_count'];
                    $this->useWifiPrint($times, $keyInfo, $content, $username, $dno);
                }
            }
        }
    }

    /**
     *使用wifi打印机打印
     * @param int $times 打印次数
     * @param string $key 加密字符串
     * @param string $content 打印内容
     * @param string $username 官网用户名
     * @param string $dno 设备编号
     * @param int $mode 打印模式（0 混合打印;1文本打印; 2二维码打印;3条码打印）
     * @param string $msgno 订单编号（不传则自动生成）
     * @param string $op 操作类型（pf:打印操作  cx：查询打印机状态 cxdd：查询订单状态）
     * @param string $qr 支付宝二维码图片链接地址（可选）
     * @return array
     */
    function useWifiPrint($times = 3, $key, $content, $username, $dno, $mode = 0, $msgno = '', $op = 'pf', $qr = '')
    {
        /**
         * 返回状态码
         * 0 成功
         * 1 订单发送失败';
         * 200 查询失败';
         * 201 不存在当前设备';
         * 300 二维码打印成功';
         * 301 二维码打印失败';
         * 401 查询订单失败';
         * 900 没有相关操作';
         * 901 操作错误';
         * -2 验证错误';
         * -3 绑定设备不属于该用户';
         * -4 打印类型错误';
         * -5 该用户无效';
         * -7 设备号';
         * -8 参数错误';
         * -102 条形码打印存在汉字';
         * -103 组合打印类型不含有前缀';
         * .
        '序号：' . ($i + 1) . '\r\n' */

        $result = array();
        for ($i = 0; $i < $times; $i++) {
            $url = 'http://121.43.235.40/WS/DealData.ashx';
            $fields = array(
                'op' => $op,
                'content' => $content .
                    '|5================================' . '\r\n' .
                    '|4   青橄榄网络技术支持',
                'key' => $key,
                'unm' => $username,
                'dno' => $dno,
                'mode' => '|' . $mode,
                'msgno' => $msgno,
                'qr' => $qr,
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, count($fields)); // 启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // 在HTTP中的“POST”操作。如果要传送一个文件，需要一个@开头的文件名

            ob_start();
            curl_exec($ch);

            $result[] = ob_get_contents();
            ob_end_clean();
        }
        return $result;
    }

    /**
     *打印信息
     * @param $orderId
     */
    public function useWifiPrintInfoTest($orderId)
    {
        wLog(date('Y-m-d H:i:s') . ' useWifiPrintInfo orderId: ' . $orderId, 'ZduRestaurantApi');
        $mOrder = D('Base/RestaurantOrder');
        $mGoods = D('Base/RestaurantGoods');
        $mWindow = D('Base/RestaurantWindow');
        //$orderId = $this->_get('order_id');
        //查询订单信息
        $info = $mOrder->relation(true)->getByPk($orderId);
        //$info = $this->mOrder->relation(true)->getByPk($orderId);

        if ($info) {
            $goods = '';
            $windowInfo = array();
            foreach ($info['RestaurantOrderGoods'] as $key => $v) {
                //查询菜品对应的种类对应档口及打印机信息
                $list = $mGoods->relation('RestaurantGoodsCategory')->getByPk($v['goods_id']);
                //$list = $this->mGoods->relation('RestaurantGoodsCategory')->getByPk($v['goods_id']);
                $wInfo = $mWindow->getByPk($list['window_id']);
                //$wInfo = $this->mWindow->getInfo($list['window_id']);
                $windowInfo[$wInfo['window_id']]['window_id'] = $wInfo['window_id'];
                $windowInfo[$wInfo['window_id']]['print_key'] = $wInfo['print_key'];
                $windowInfo[$wInfo['window_id']]['print_dno'] = $wInfo['print_dno'];
                $windowInfo[$wInfo['window_id']]['print_username'] = $wInfo['print_username'];
                $windowInfo[$wInfo['window_id']]['print_count'] = $wInfo['print_count'];

                $goods = $goods . $v['goods_name'] . '…' . $v['goods_amount'] . '*' . $v['goods_num'] . '）\r\n';
            }

            $headerStr = '';
            if ($this->accountId == 2) {
                $headerStr = '|2http://weixin.qq.com/r/7UzVzQPEGF5nrUeu9xn-' . '\r\n';
            }
            if ($windowInfo) {
                foreach ($windowInfo as $val) {
                    $content = $headerStr .
                        '|5================================' . '\r\n' .
                        '餐厅名：' . $info['RestaurantInfo']['restaurant_name'] . '\r\n' .
                        '订单号：' . $info['order_sn'] . '\r\n' .
                        '桌号：' . $info['order_num'] . '\r\n' .
                        '订单内容：\r\n' . $goods .
                        '总计：' . $info['order_amount'] . '\r\n' .
                        '就餐时间：' . $info['send_time'] . '\r\n' .
                        '备注：' . $info['memo'] . '\r\n';
                    $str = $val['print_key'] . $val['print_dno'] . 'aykj';
                    $keyInfo = md5($str);
                    $username = $val['print_username'];
                    $dno = $val['print_dno'];
                    $times = $val['print_count'];
                    $this->useWifiPrint($times, $keyInfo, $content, $username, $dno);
                }
            }
        }
    }

    /**
     *使用wifi打印机打印
     * @param int $times 打印次数
     * @param string $key 加密字符串
     * @param string $content 打印内容
     * @param string $username 官网用户名
     * @param string $dno 设备编号
     * @param int $mode 打印模式（0 混合打印;1文本打印; 2二维码打印;3条码打印）
     * @param string $msgno 订单编号（不传则自动生成）
     * @param string $op 操作类型（pf:打印操作  cx：查询打印机状态 cxdd：查询订单状态）
     * @param string $qr 支付宝二维码图片链接地址（可选）
     * @return array
     */
    function useWifiPrintTest($times = 3, $key, $content, $username, $dno, $mode = 0, $msgno = '', $op = 'pf', $qr = '')
    {
        /**
         * 返回状态码
         * 0 成功
         * 1 订单发送失败';
         * 200 查询失败';
         * 201 不存在当前设备';
         * 300 二维码打印成功';
         * 301 二维码打印失败';
         * 401 查询订单失败';
         * 900 没有相关操作';
         * 901 操作错误';
         * -2 验证错误';
         * -3 绑定设备不属于该用户';
         * -4 打印类型错误';
         * -5 该用户无效';
         * -7 设备号';
         * -8 参数错误';
         * -102 条形码打印存在汉字';
         * -103 组合打印类型不含有前缀';
         * */
        $result = array();
        for ($i = 0; $i < $times; $i++) {
            $url = 'http://121.43.235.40/WS/DealData.ashx';
            $fields = array(
                'op' => $op,
                'content' => $content .
                    '序号：' . ($i + 1) . '\r\n' .
                    '================================' . '\r\n' .
                    '|4技术支持：杭州青橄榄网络技术有限公司',
                'key' => $key,
                'unm' => $username,
                'dno' => $dno,
                'mode' => '|' . $mode,
                'msgno' => $msgno,
                'qr' => $qr,
            );
            wLog(date('Y-m-d H:i:s') . ' orderPay resCampus xlh api usewifi: ' . $url.var_export($fields,true), 'ZduRestaurantApi');
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, count($fields)); // 启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // 在HTTP中的“POST”操作。如果要传送一个文件，需要一个@开头的文件名

            ob_start();
            curl_exec($ch);

            $result[] = ob_get_contents();
            ob_end_clean();
        }
        return $result;
    }

    /**
     * 错误提示
     */
    public function error($tips = '页面加载中', $times = 2, $url = "" ,$noRedirect = 0)
    {
        $times = $times * 1000;
        $this->assign('tips', $tips);
        $this->assign('times', $times);
        if ($url == '') {
            $url = "/base/center/center/account_id/" . $this->accountId;
        }
        $this->assign('url', $url);
        $this->assign("no_redirect",$noRedirect);
        $this->display($this->module_name . ':error');
        exit;
    }


    /**
     *定时任务处理
     */
    public function timeTask()
    {
        $list = $this->mRestaurant->getList(array('res_id' => $this->resId));
        if ($list) {
            foreach ($list as $v) {
                $this->receive($this->resId, $v['receive_time'], $v['comment_time']);
            }
        }
    }

    /**
     *发货5天自动确认收货
     */
    public function receive($resId, $receiveTime, $commentTime)
    {
        set_time_limit(0);
        //查询已发货超过设置天数的订单号
        $list = $this->mOrder->getList(array('res_id' => $resId, 'status' => 2, 'ship_time' => array('lt', time() - $receiveTime * 3600)), array('order_id'));

        $orderIdList = array();
        if ($list) {
            foreach ($list as $v) {
                $orderIdList[] = $v['order_id'];
            }
        }

        if ($orderIdList) {
            //批量自动确认收货
            $this->mOrder->where(array('order_id' => array('in', $orderIdList)))->save(array('status' => 3, 'receive_time' => time()));
        }

        $this->commentOrder($resId, $commentTime);
        $this->close($this->resId);
    }

    /**
     *确认收货15天自动好评(全部5星好评，文件评价为“好评”)
     */
    public function commentOrder($resId, $commentTime)
    {
        set_time_limit(0);
        //查询收货后需要在设置天数自动好评的订单
        $list = $this->mOrder->getList(array('res_id' => $resId, 'status' => 3, 'receive_time' => array('lt', time() - $commentTime * 3600)), array('order_id', 'restaurant_id'));

        $orderList = array();
        if ($list) {
            foreach ($list as $v) {
                $orderList[] = $v['order_id'];
                $this->mRestaurantInfo->comment(array('restaurant_id' => $v['restaurant_id']), 5, 5, 5);
            }
        }

        if ($orderList) {
            //批量评价
            $this->mOrder->where(array('order_id' => array('in', $orderList)))->save(array('status' => 4, 'finish_time' => time(), 'comment' => '好评'));
        }
    }

    /**
     *关闭未付款订单
     */
    public function close($resId)
    {
        //查询在设置时间数自动关闭的订单
        if (time() >= strtotime(date('Y-m-d 22:00:00')) && time() < strtotime(date('Y-m-d')) + 86400) {
            $list = $this->mOrder->getList(array('res_id' => $resId, 'status' => 0), array('order_id', 'restaurant_id'));

            $orderList = array();
            if ($list) {
                foreach ($list as $v) {
                    $orderList[] = $v['order_id'];
                }
            }
            if ($orderList) {
                //批量关闭
                $this->mOrder->where(array('order_id' => array('in', $orderList)))->save(array('status' => 8, 'close_time' => time(), 'close_reason' => '超时未付款'));
            }
        }
    }
}